import uuid
from typing import Optional

from fastapi import APIRouter, Body, HTTPException, UploadFile, File, Form
from pydantic import BaseModel, Field, ValidationError

from app.core.chains import get_introduction_practice_chain
from app.core.memory.memory_manager import get_session_history

router = APIRouter()


class Resume_Evaluate_Request(BaseModel):
    position_id: int = Field(..., description="ID of the position the user is applying for.")
    resume: UploadFile = File(..., description="上传的简历文件")
    conversation_id: Optional[str] = Field(None,
                                           description="A unique ID for the conversation. If not provided, a new one will be generated.")

class Resume_Evaluate_Response(BaseModel):
    answer: str
    conversation_id: str


@router.post("/", response_model=Resume_Evaluate_Response)
def knowledge_base_chat(request_data: dict = Body(...)):
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    try:
        # 手动验证请求数据
        request = Resume_Evaluate_Request(**request_data['content'])
    except ValidationError as e:
        # 打印详细的验证错误
        print(f"请求数据验证失败: {e.errors()}")
        print(f"收到的请求数据: {request_data}")
        raise HTTPException(status_code=422, detail=e.errors())
    position_list=["软件工程师","软件测试员"]
    conv_id = request.conversation_id or str(uuid.uuid4())
    print(f"--- KB Chat endpoint called for conversation_id: {conv_id} ---")
    # 获取用户应聘岗位
    position_id = request.position_id or str(uuid.uuid4())
    position = position_list[position_id]
    print(f"用户应聘岗位为：{position}")
    chat_history_backend = get_session_history(conv_id)
    introduction_practice_chain = get_introduction_practice_chain()

    enhanced_query = (
        f"用户应聘的岗位为: {position}\n"
        f"用户输入的自我介绍为: {request.self_intro}\n"
    )
    print('enhanced_query:', enhanced_query)


    result = introduction_practice_chain.invoke({
        "input": enhanced_query,
        "chat_history": chat_history_backend.messages
    })

    answer = result.get("answer", "I'm sorry, I couldn't find an answer.")
    print(f"{answer}")
    chat_history_backend.add_user_message(enhanced_query)
    chat_history_backend.add_ai_message(answer)

    return Resume_Evaluate_Response(
        answer=answer,

        conversation_id=conv_id
    )


from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os
from docx import Document
import uuid

app = Flask(__name__)

# 配置上传文件夹和允许的扩展名
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'docx', 'doc'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def docx_to_text(file_path):
    """将Word文档转换为纯文本"""
    try:
        doc = Document(file_path)
        full_text = []
        for para in doc.paragraphs:
            full_text.append(para.text)
        return '\n'.join(full_text)
    except Exception as e:
        raise RuntimeError(f"Word文件处理失败: {str(e)}")


@router.post("/", response_model=Resume_Evaluate_Response)
def evaluate_resume():
    # 检查文件是否在请求中
    if 'resume' not in request.files:
        return jsonify({
            "success": False,
            "error": "未上传文件"
        }), 400

    file = request.files['resume']

    # 检查文件名是否有效
    if file.filename == '':
        return jsonify({
            "success": False,
            "error": "无效文件名"
        }), 400

    # 检查文件扩展名
    if not allowed_file(file.filename):
        return jsonify({
            "success": False,
            "error": "不支持的文件类型"
        }), 400

    try:
        # 安全保存文件
        filename = secure_filename(file.filename)
        unique_name = f"{uuid.uuid4().hex}_{filename}"
        save_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_name)
        file.save(save_path)

        # 获取表单数据
        position_id = request.form.get('position_id', default=1, type=int)
        conversation_id = request.form.get('conversation_id', default=None)

        # 转换为文本
        resume_text = docx_to_text(save_path)

        # 这里可以添加简历评估逻辑
        # 使用position_id、conversation_id和resume_text进行处理...

        # 模拟评估结果
        evaluation = {
            "score": 85,
            "summary": "简历内容完整，相关经验匹配",
            "suggestions": ["建议增加项目量化成果", "补充技能证书信息"]
        }

        # 清理临时文件
        os.remove(save_path)

        # 构建响应
        response = {
            "success": True,
            "evaluation": evaluation,
            "position_id": position_id,
            "conversation_id": conversation_id or str(uuid.uuid4())
        }

        return jsonify(response)

    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500


if __name__ == '__main__':
    app.run(debug=True)
